<?php

//App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 * @property User $Profile
 * @property PaginatorComponent $Paginator
 */
App::uses('CakeEmail', 'NetWork/Email');

class UsersController extends AppController
{

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator', 'Auth', 'Email');

    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow('add', 'login', 'logout');
        $this->Auth->autoRedirect = false;
    }

    public function isAuthorized($user)
    {

        if (in_array($this->action, array('edit', 'delete')))
        {
            if ($user['id'] != $this->request->params['pass'][0])
            {
                return false;
            }

            if ($user['id'] == 20)
            {
                return true;
            }
        }
        return true;
    }

    public function login()
    {

        //if already logged-in, redirect
        if ($this->Session->check('Auth.User'))
        {
            $this->redirect(array('action' => 'index'));
            $this->Session->write('userInfo', CakeSession::read('currentUser'));
        }
        if ($this->request->is('post'))
        {

            if ($this->Auth->login())
            {
                $this->redirect($this->Auth->redirectUrl());
            } else
            {
                $this->Session->setFlash(__('Invalid emaill or password'), 'alert-danger');
            }
        }
    }

    public function logout()
    {
        date_default_timezone_set("Asia/Ho_Chi_Minh");
        $date = date("Y-m-d H:i:s");
        $id = $this->Auth->user('id');
        $this->User->save(array('id' => $id, 'last_access' => $date));
        $this->Session->destroy();
        $this->redirect($this->Auth->redirect());
    }

    /**
     * index method
     *
     * @return void
     */
    public function index()
    {
        if ($this->Auth->user('status') != 0)
        {
            $this->Session->setFlash('Please active email to login!', 'alert-danger');
            $this->redirect(array('action' => 'logout'));
        } else
        {
            if ($this->Session->check('Auth.User'))
            {
                $this->User->recursive = 1;
                $this->set('users', $this->Paginator->paginate());
                // debug($this->Paginator->paginate());
                $sql = "SELECT * FROM tb_profiles As pr, tb_users as u WHERE u.id= pr.users_id";
                $this->loadModel('Profile');
                //debug($this->Profile->query($sql));
                $users = $this->Profile->query($sql);
                $this->set('profiles', $users);
            } else
            {
                $this->redirect('login');
            }
        }
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null)
    {
        if (!$this->User->exists($id))
        {
            throw new NotFoundException(__('Invalid user'));
        }
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->set('user', $this->User->find('first', $options));
        $this->set('userId', $this->Session->read('User.id'));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add()
    {
        date_default_timezone_set("Asia/Ho_Chi_Minh");
        if ($this->request->is('post'))
        {
            //destroy session
            $this->Session->destroy();
            $data = $this->request->data;

            //create status random unique to send mail and active
            $data['User']['status'] = md5(uniqid(rand(), true));
            $status = $data['User']['status'];

            $this->User->create();
            if ($this->User->save($data))
            {
                //get data from form register: to send email:email, name
                $id = $this->User->id;
                $email = $data['User']['email'];
                $name = $data['User']['username'];

                //insert user_id to Profile table
                $this->loadModel('Profile');
                $sql = "INSERT INTO tb_profiles(users_id) VALUES ({$id})";
                $this->Profile->query($sql);

                //validate send mail and show result
                if ($this->send_email($email, $name, $status))
                {
                    $this->Session->setFlash(__('The user has been saved. Please confirm link active account in email: <kbd>' . $email . '</kbd> to login'), 'alert-success');
                    return $this->redirect(array('action' => 'login'));
                } else
                {
                    $this->Session->setFlash(__('Something wrong! when sent email: <kbd>' . $email . '</kbd>'), 'alert-danger');
                }
            } else
            {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'alert-danger');
            }
        }
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param int $id
     * @return void
     */
    public function edit($id = null)
    {
        if (!$this->User->exists($id))
        {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is(array('put')))
        {
            $this->User->id = $id;
            $data = $this->request->data;
            $data['User']['id'] = $id;
            if ($this->User->save($data))
            {
                $this->Session->setFlash(__('The user has been updated.'), 'alert-success');
                return $this->redirect(array('action' => 'index'));
            } else
            {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'alert-danger');
            }
        } else
        {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param int $id
     * @return void
     */
    public function delete($id = null)
    {
        $this->User->id = $id;
        if (!$this->User->exists())
        {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->User->delete())
        {
            $this->Session->setFlash(__('The user has been deleted.'), 'alert-success');
        } else
        {
            $this->Session->setFlash(__('The user could not be deleted. Please, try again.'), 'alert-danger');
        }
        return $this->redirect(array('action' => 'index'));
    }

    /**
     * activate email method
     * 
     * @param string $status
     * @return void
     */
    public function activate($status = null)
    {
        if ($status == '' || $status == null)
        {
            $this->Session->setFlash('Error', 'alert-danger');
            $this->redirect(array('action' => 'login'));
        } else
        {
            //get information user have $status
            $user = $this->User->find('first', array('conditions' => array('User.status' => $status)));
            //Active ->Update status = 0
            if ($this->User->save(array('id' => $user['User']['id'], 'status' => 0)))
            {
                $user['User']['status'] = 0;
                if ($this->Auth->login($user['User']))
                {
                    $this->Session->setFlash('Activate Success Fully!!', 'alert-success');
                    $this->redirect($this->Auth->redirectUrl());
                }
            } else
            {
                $this->Session->setFlash('Activate Error!!!', 'alert-danger');
                $this->redirect(array('action' => 'login'));
            }
        }
    }

    /**
     * send email method
     * 
     * @param string $email name
     * @param string $name
     * @param string status
     * @return boolean
     */
    public function send_email($emailname, $name, $status)
    {
        $email = new CakeEmail();
        $email->config('gmail');
        $email->from('thienbv91@gmail.com');
        $email->to($emailname);
        $email->subject('Mail Confirmation Money LoVe Account'); //title of email
        $email->template('email_tpl'); //set template  
        $email->viewVars(array('name' => $name, 'emailname' => $emailname, 'status' => $status)); //pass variable to template
        $email->emailFormat('html');
        if ($email->send())
        {
            return true;
        } else
        {
            return false;
        }
    }

    /**
     * send_mail_pass password method
     * @param string $name
     * @param string $emailname
     * @param string $pass
     * @return boolean
     */
    public function send_mail_pass($name, $emailname, $pass)
    {
        $email = new CakeEmail();
        $email->config('gmail');
        $email->from('thienbv91@gmail.com');
        $email->to($emailname);
        $email->subject('Reset password moneylover: ' . $emailname);
        $email->template('resetpass');
        $email->viewVars(array('name' => $name, 'emailname' => $emailname, 'pass' => $pass));
        $email->emailFormat('html');
        if ($email->send())
        {
            return true;
        } else
        {
            return false;
        }
    }

    /**
     * resest password method
     * @return void
     */
    public function resetpassword()
    {
        if ($this->request->is('post'))
        {
            $data = $this->request->data;
            $email = $data['User']['email'];
            $user = $this->User->find('first', array('conditions' => array('User.email' => $email), 'recursive' => 0));
            //debug($user);die();
            if ($user === null)
            {
                $this->Session->setFlash('Email not existes!', 'alert-danger');
                $this->redirect(array('action' => 'resetpass'));
            } else
            {

                $pass = $this->gener_password(6);
                $id = $user['User']['id'];
                $name = $user['User']['username'];

                if ($this->User->save(array('id' => $id, 'password' => $pass, 'password_confirm' => $pass)))
                {
                    if ($this->send_mail_pass($name, $email, $pass))
                    {
                        $this->Session->setFlash('Resest password successfully!, Please check email to get pass', 'alert-success');
                        $this->redirect(array('action' => 'login'));
                    } else
                    {
                        $this->Session->setFlash('Resest password Error!', 'alert-danger');
                        $this->redirect(array('action' => 'resetpassword'));
                    }
                }
            }
        }
    }

    /**
     * gener password method
     * @param int length password
     * @return randomPassword
     */
    public function gener_password($length = 6)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++)
        {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

}
